package other.edan.system.k3;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.edan.system.client.EdanK3Utils;
import other.edan.system.utils.ComUtils;
import other.edan.system.utils.HCXObjectService;
import other.edan.system.utils.ResultBody;
import other.edan.system.utils.TfReturnMsgTools;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 推送客户数据到k3
 * @Author 黎炎松
 * 2024-06-12 09:49
 */
@RestApi(baseUrl = "/xsy/account")
public class PushAccount implements Trigger, ApprovalEvent {
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步客户数据到k3 ==> ";

    /**
     * trigger 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Account> accountList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Account account = (Account) xObject;
            accountList.add(account);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        syncAccountToK3(accountList.get(0));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * 审批流触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());
        logger.info(request.toString());
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");

        // 执行同步逻辑
        Account account = new Account();
        account.setId(request.getDataId());
        account = HCXObjectService.get(account);
        syncAccountToK3(account);

        return response;
    }


    /**
     * 手动同步客户数据到k3
     * @param id
     * @return
     */
    @RestMapping(value = "/syncK3", method = RequestMethod.POST)
    public String syncK3(@RestQueryParam(name = "id") Long id){
        logger.info(LOGGER_MSG + "执行了按钮事件：" + id);
        Account account = new Account();
        account.setId(id);
        account = HCXObjectService.get(account);
        return syncAccountToK3(account);
    }

    public static void main(String[] args) throws ApiEntityServiceException, CacheException {
        Account account = new Account();
        account.setId(3587547598018960L);
        account = HCXObjectService.get(account);
        new PushAccount().syncAccountToK3(account);
    }

    /**
     * 同步客户到k3
     * @param account
     */
    public String syncAccountToK3(Account account){
        try {
            logger.info(LOGGER_MSG + "处理开始: " + account);

            // 判断是 渠道 类型的进行同步
            //Long entityType = account.getEntityType();
            //if (entityType != 3420557285530070L) {
            //    logger.error(LOGGER_MSG + "当前不是渠道客户,无需推送");
            //    return TfReturnMsgTools.getFailResult("Currently not a channel customer, no need to push");
            //}
            JSONObject accountDesc = ComUtils.getEntityDesc("account");
            Map<String, String> partnersOpt = ComUtils.getMapsFromDescribeJson(accountDesc, "partnerAttribute__c", "value", "apiKey"); // 合作伙伴属性
            Map<String, String> partnersTypeOpt = ComUtils.getMapsFromDescribeJson(accountDesc, "partnerClassificationType__c", "value", "apiKey"); // 合作伙伴分类类型

            // 拼接数据
            JSONObject reqData = new JSONObject();
            reqData.put("fNumber", account.getCustomerCodeNumber__c()); // 编号
            reqData.put("fName", account.getAccountName()); // 名称
            reqData.put("fEmail", account.getCustomerEmail__c()); // 联系邮箱
            reqData.put("fPhone", account.getPhone()); // 联系电话
            reqData.put("fAddress", account.getAddress()); // 地址
            reqData.put("fAccount", account.getBankAccount__c()); // 银行账号 --
            reqData.put("fTaxNum", account.getTaxRegistrationNo__c()); // 税务登记号 --
            reqData.put("fRegionCode", 113); // 应收账款科目代码 account.getFRegionCode__c()
            reqData.put("fCrmNumber", account.getCustomerCodeNumber__c()); // crm编码
            reqData.put("f122", account.getCreatedAt()); // 创建日期
            reqData.put("fStatus", 1072); // 客户状态

            // reqData.put("fBank", account.getFBank__c()); // 开户银行 --
            // reqData.put("fContact", account.getFContact__c()); // 联系人 --
            // reqData.put("fDeleted", account.getFDeleted__c()); // 是否删除 --
            // reqData.put("fARAccountCode", account.getFARAccountCode__c()); // 区域代码 --
            // reqData.put("f108", account.getUnifiedSocialCreditIdentifier__c()); // 经营许可证号 --

            // 客户AEO证书编号
            String certificateNo = account.getCertificateNo__c();
            reqData.put("f107", Objects.equals(certificateNo, "/") ? "无" : certificateNo);

            // 合规性文件管控
            List<Map> fileList = account.getBusinessLicense__c();
            reqData.put("f109", fileList != null && fileList.size() > 0 ? true : false);

            // 是否属于美国实体管制清单
            Integer isGzqd = account.getUnitedStatesControlList__c();
            reqData.put("f132", Objects.equals(isGzqd, 1) ? true : false);

            // 是否停止出货
            Integer isTzch = account.getTradingClientsAreNotAllowed__c();
            reqData.put("f134", Objects.equals(isTzch, 1) ? true : false);

            // 合作伙伴属性
            Integer partnerAttribute = account.getPartnerAttribute__c();
            if (partnerAttribute != null) {
                reqData.put("f139", Integer.valueOf(partnersOpt.get(partnerAttribute.toString())));
            }

            // 合作伙伴分类类型
            Integer partnerClassificationType = account.getPartnerClassificationType__c();
            if (partnerClassificationType != null) {
                reqData.put("f140", Integer.valueOf(partnersTypeOpt.get(partnerClassificationType.toString())));
            }

            // 国家k3编码
            String guoJiaK3Code = account.getGuoJiaK3Code__c();
            if (StringUtils.isNotBlank(guoJiaK3Code)) {
                reqData.put("f102", guoJiaK3Code);
            }

            logger.error(LOGGER_MSG + "推送的客户数据:" + reqData);

            // 记录同步状态
            Account upAccount = new Account();
            upAccount.setId(account.getId());
            upAccount.setSyncStatus__c(2); // 同步状态 1：待同步 2：成功 3：失败
            upAccount.setFailureReasons__c("");

            // 推送数据到k3
            ResultBody resultBody = EdanK3Utils.sendPost(reqData, EdanK3Utils.ADD_UP_ACCOUNT_TEST_URL, "");
            if (!Objects.equals(resultBody.getCode(), "200")) {
                String errMsg = resultBody.getMessage();

                upAccount.setSyncStatus__c(3); // 同步状态 1：待同步 2：成功 3：失败
                upAccount.setFailureReasons__c(errMsg); // 失败原因
                OperateResult update = HCXObjectService.update(upAccount);
                logger.info(LOGGER_MSG + "更新同步状态: " + update.getSuccess());

                logger.error(LOGGER_MSG + "处理失败:" + errMsg);
                return TfReturnMsgTools.getFailResult("Push failed:" + errMsg);
            }

            // 更新同步状态 & 更新用户K3编码
            Object result = resultBody.getResult();
            if (result != null) {
                upAccount.setK3Code__c(result.toString());
            }
            logger.info(LOGGER_MSG + "upAccount: " + upAccount);
            OperateResult update = HCXObjectService.update(upAccount);
            logger.info(LOGGER_MSG + "更新同步状态: " + update.getSuccess());

            logger.info(LOGGER_MSG + "推送成功");
            return TfReturnMsgTools.getSuccessResult("Push successful");
        } catch (Exception e) {
            logger.info(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("Push exception:" + e.getMessage());
        }
    }


}
